package com.wushi.lenovo.asia5b.app_ui.good.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.mvp.base.BaseMvpActivity;
import com.mvp.utils.ToastUtil;
import com.mvp.utils.https.MapHelper;
import com.wushi.lenovo.asia5b.R;
import com.wushi.lenovo.asia5b.app_config.CommonConstant;
import com.wushi.lenovo.asia5b.app_di.APPComponentFactory;
import com.wushi.lenovo.asia5b.app_di.goods.mvpview.DiffCheckActivityView;
import com.wushi.lenovo.asia5b.app_di.goods.presenter.DiffCheckActivityPresenter;
import com.wushi.lenovo.asia5b.app_event.ChangeAddressEvent;
import com.wushi.lenovo.asia5b.app_event.FacebookEvent;
import com.wushi.lenovo.asia5b.app_event.NewAddressEvent;
import com.wushi.lenovo.asia5b.app_event.OrderPayEvent;
import com.wushi.lenovo.asia5b.app_model.credit.bean.TopupInfoBean;
import com.wushi.lenovo.asia5b.app_model.good.OrderPayPriceModel;
import com.wushi.lenovo.asia5b.app_model.good.PaymentMethodModel;
import com.wushi.lenovo.asia5b.app_model.good.ShopModel;
import com.wushi.lenovo.asia5b.app_model.good.bean.StepHelper;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModel;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.GoodsModelIml;
import com.wushi.lenovo.asia5b.app_model.good.goodbean.OrderGoodBean;
import com.wushi.lenovo.asia5b.app_model.other.WebUrlType;
import com.wushi.lenovo.asia5b.app_model.profile.AddressModel;
import com.wushi.lenovo.asia5b.app_ui.good.adapter.OrderPaymentMethodAdapter;
import com.wushi.lenovo.asia5b.app_ui.good.view.OrderAddressView;
import com.wushi.lenovo.asia5b.app_ui.pay.activity.PayActivity;
import com.wushi.lenovo.asia5b.app_ui.shopcar.adapter.OrderPackGoodsAdapter;
import com.wushi.lenovo.asia5b.app_utils.eye.EyeUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * Created by zhangyuncai on 2020/3/6.
 * 二次付款
 */
public class DiffCheckActivity extends BaseMvpActivity<DiffCheckActivityView, DiffCheckActivityPresenter> implements DiffCheckActivityView {
    @BindView(R.id.tv_ordercheck_billingaddress)
    TextView tv_ordercheck_billingaddress;
    @BindView(R.id.billingaddress_ordercheck)
    OrderAddressView billingaddress_ordercheck;
    @BindView(R.id.tv_ordercheck_paymentmethos)
    TextView tv_ordercheck_paymentmethos;
    @BindView(R.id.rv_ordercheck_paymentmethos)
    RecyclerView paymentRecyclerView;
    @BindView(R.id.rv_ordercheck_goods)
    RecyclerView rv_ordercheck_goods;
    @BindView(R.id.bt_ordercheck_submit)
    Button bt_ordercheck_submit;
    @BindView(R.id.tv_ordercheck_notice)
    TextView tv_ordercheck_notice;
    @BindView(R.id.ll_ordercheck_bottom)
    LinearLayout ll_ordercheck_bottom;
    @BindView(R.id.view_ordercheck_empty)
    View view_ordercheck_empty;
    @BindView(R.id.tv_ordercheck_totalprice)
    TextView tv_ordercheck_totalprice;

    //收货地址
    private AddressModel addressModel;
    //价格详细
    private OrderPayPriceModel orderPayPriceModel;

    private final MapHelper extraMap = MapHelper.newHashMap();
    private OrderPackGoodsAdapter orderPackGoodsAdapter;
    private List<OrderGoodBean> inputGoods;
    public static void startDiffCheckActivity(Context context, Serializable serializable,Serializable goods) {
        Intent intent = new Intent(context, DiffCheckActivity.class);
        intent.putExtra("datas", serializable);
        intent.putExtra("goods", goods);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_diffcheck;
    }

    @Override
    protected void constructComponent() {
        APPComponentFactory.getAppBaseComponent().inject(this);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        List<Integer> idList = (List<Integer>) getIntent().getSerializableExtra("datas");
        inputGoods= (List<OrderGoodBean>) getIntent().getSerializableExtra("goods");
        getPresenter().addGoods(idList);
        if (idList == null || idList.size() <= 0) {
            return;
        }
        initView();

        initData();

        initEvent();
    }

    @Override
    protected void initView() {

        EyeUtils.setLinkText(mActivity, getString(R.string.shopcar_pi_notice), getString(R.string.shopcar_pi_notice_key),
                tv_ordercheck_notice, WebUrlType.shopcar_pi);

        //步骤1/2/3
        int i = 0;
        tv_ordercheck_billingaddress.setText(StepHelper.getStep(getString(R.string.billingaddress), i++));
        tv_ordercheck_paymentmethos.setText(StepHelper.getStep(getString(R.string.paymentmethod), i++));

//        setGoodsView(inputGoods);

    }

    protected <GOOD extends GoodsModelIml> void setGoodsView(List<GOOD> goodsList) {
        /**
         * 显示商品列表
         */
        if (orderPackGoodsAdapter == null && goodsList != null) {
            orderPackGoodsAdapter = new OrderPackGoodsAdapter(goodsList);
            orderPackGoodsAdapter.inputGoods=inputGoods;
            rv_ordercheck_goods.setLayoutManager(new LinearLayoutManager(mActivity));
            rv_ordercheck_goods.setAdapter(orderPackGoodsAdapter);
        }
    }

    /**
     * 设置支付方式
     *
     * @param payments
     */
    public void setPaymentMethodView(List<PaymentMethodModel.PaymentsBean> payments) {
        OrderPaymentMethodAdapter paymentAdapter = new OrderPaymentMethodAdapter(payments == null ? new ArrayList() : payments);
        paymentRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        paymentRecyclerView.setAdapter(paymentAdapter);
        paymentAdapter.setOnItemClickListener((adapter, view, position) -> {
            PaymentMethodModel.PaymentsBean bean = (PaymentMethodModel.PaymentsBean) paymentAdapter.getItem(position);
            if (paymentAdapter.getSelectPosition() != position) {
                extraMap.put("payment_method", bean.getCode());
                getCharges();//③
            }
            paymentAdapter.setSelectPosition(position);
        });
    }

    /**
     * 设置价格详细
     *
     * @param orderPayPriceModel
     */
    private void setPriceDetailView(OrderPayPriceModel orderPayPriceModel) {
        this.orderPayPriceModel = orderPayPriceModel;
        if (orderPayPriceModel != null) {
            List<ShopModel> shops = orderPayPriceModel.shops;
            if (shops != null) {
                List<GoodsModel> goodsModels = new ArrayList<>();
                for (ShopModel shop : shops) {
                    if (shop.products != null) {
                        goodsModels.addAll(shop.products);
                    }
                }
                setGoodsView(goodsModels);
            }

            tv_ordercheck_totalprice.setText(orderPayPriceModel.getTotal_text());
        } else {
            tv_ordercheck_totalprice.setText("-");
        }
        bt_ordercheck_submit.setEnabled(orderPayPriceModel != null);
    }

    @Override
    protected void initData() {
        getCharges();
    }

    /**
     * 获取商品列表价格
     * ①派送方式变化时
     * ②支付方式变化时
     * ③保险复选框变化时
     * ④优惠券变化时
     */
    private void getCharges() {
        extraMap.put("insurance", "null");
        extraMap.put("voucher", "null");
        extraMap.put("local_delivery_method", "");
        extraMap.put("international_delivery_method", "");
        getPresenter().getCharges(extraMap);
    }

    @Override
    protected void initEvent() {
    }

    @OnClick({
            R.id.view_ordercheck_empty,
            R.id.bt_ordercheck_submit
    })
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            /**
             * 防止点击穿透到下层
             */
            case R.id.view_ordercheck_empty:
                break;
            /**
             * 支付
             */
            case R.id.bt_ordercheck_submit: {
                if (addressModel == null) {
                    ToastUtil.showToast(getString(R.string.orderpayment_fillup_address_billing));
                    return;
                }
                if (orderPayPriceModel != null && orderPayPriceModel.getExtra_data() != null && !TextUtils.isEmpty(orderPayPriceModel.getExtra_data().payment_method)) {
                    String payCode = orderPayPriceModel.getExtra_data().payment_method;
                    //支付方式
                    TopupInfoBean topupInfoBean = new TopupInfoBean();
                    topupInfoBean.OrderPaymentType=TopupInfoBean.OrderPaymentType_diff;
                    topupInfoBean.setCheckout_log_id(orderPayPriceModel.getCheckout_log_id());
                    String total = orderPayPriceModel.getTotal();
                    topupInfoBean.setTotalAmount(total);
                    Intent intent = new Intent(mActivity, PayActivity.class);
                    intent.putExtra(CommonConstant.TopupInfoBean, topupInfoBean);
                    intent.putExtra("payCode", payCode);
                    startActivity(intent);
                } else {
                    ToastUtil.showToast("payCode is error!");
                }

            }
            break;
            default:
                break;
        }

    }



    @Override
    public void getPaymentMethodsResult(List<PaymentMethodModel.PaymentsBean> paymentsBeans) {
        setPaymentMethodView(paymentsBeans);
    }

    @Override
    public void getAddressModelResult(AddressModel addressModel) {
        this.addressModel = addressModel;
        billingaddress_ordercheck.setAddressView(addressModel);
    }

    @Override
    public void getChargesResult(OrderPayPriceModel orderPayPriceModel) {
        view_ordercheck_empty.setVisibility(View.GONE);
        setPriceDetailView(orderPayPriceModel);
    }


    /**
     * 地址改动通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onChangeAddress(ChangeAddressEvent event) {
        if (event != null && event.addressModel != null) {
            this.addressModel = event.addressModel;
            billingaddress_ordercheck.setAddressView(addressModel);
            extraMap.clear();
            getPresenter().addressModel = addressModel;
            getCharges();
        }


    }

    /**
     * 新建地址通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onNewAddressEvent(NewAddressEvent event) {
        if (event != null) {
            if (addressModel == null) {
                extraMap.clear();
                getCharges();
            }
        }


    }

    /**
     * 支付后通知
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN) //在ui线程执行
    public void onOrderPayEventEvent(OrderPayEvent event) {


        if (event != null) {
            if (event.resultModel.isSuccess()) {
                if (orderPayPriceModel != null) {
                    FacebookEvent.Companion.ordetPayment(orderPayPriceModel.getTotal());
                }
                finish();
            } else {//支付失败后,重新加载数据
                getCharges();
            }
        }

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
